package com.phattaradanai.ekardex;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.phattaradanai.ekardex.HN_Profile.CHN_Profile;

import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.text.*;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.content.Intent;

public class Main_Activity extends Activity implements
	NavigationDrawerFragment.NavigationDrawerCallbacks 
{
	public static boolean get_HN = false;
	
	
	/**
	* Fragment managing the behaviors, interactions and presentation of the
	* navigation drawer.
	*/
	private NavigationDrawerFragment mNavigationDrawerFragment;
	
	/**
	* Used to store the last screen title. For use in
	* {@link #restoreActionBar()}.
	*/
	private CharSequence mTitle;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
				.findFragmentById(R.id.navigation_drawer);
		mTitle = getTitle();

		// Set up the drawer.
		mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
				(DrawerLayout) findViewById(R.id.drawer_layout));
		
		/*Create Get ID Fragment */
		Find_ID findID_Fragment = new Find_ID();
		FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.replace	(android.R.id.content, findID_Fragment, "getIDFragement");
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragmentTransaction.commit();
			
	}
	
	@Override
	public void onNavigationDrawerItemSelected(int position) 
	{
		// update the main content by replacing fragments
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager
				.beginTransaction()
				.replace(R.id.container,
						PlaceholderFragment.newInstance(position + 1)).commit();
	}
	
	public void onSectionAttached(int number) 
	{
		switch (number) 
		{
			case 1:
				mTitle = getString(R.string.eKardex);
				break;
			case 2:
				//mTitle = getString(R.string.coming_soon);
				break;
			case 3:
				/* About section*/
				final AlertDialog.Builder aboutDialog = new AlertDialog.Builder(this);
				
				aboutDialog.setTitle("About");
				aboutDialog.setMessage("eKardex version 1.0 \r\n\r\nDeveloped by P. Kiratiwudhikul\r\nElectrical Enginerring Department\r\nMahidol University");
				aboutDialog.setPositiveButton("Close", null);
				aboutDialog.show();
				break;
			case 4:
				/* Logout */
				//mTitle = getString(R.string.Logout);	
				startActivity(new Intent(this, LoginActivity.class));
				break;
		}
	}
		
	public void doPositiveClick(){
		
	}
	
	public void restoreActionBar() 
	{
		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(mTitle);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		if (!mNavigationDrawerFragment.isDrawerOpen()) 
		{
			// Only show items in the action bar relevant to this screen
			// if the drawer is not showing. Otherwise, let the drawer
			// decide what to show in the action bar.
			getMenuInflater().inflate(R.menu.main, menu);
			restoreActionBar();
			return true;
		}
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) 
		{
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	/**
	* A placeholder fragment containing a simple view.
	*/
	public static class PlaceholderFragment extends Fragment 
	{
		/* Define Global Variable */
		public final boolean get_HN = false;
		
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		private final static String ARG_SECTION_NUMBER = "section_number";
		
		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static  PlaceholderFragment newInstance(int sectionNumber) 
		{
			PlaceholderFragment fragment = new PlaceholderFragment();
			Bundle args = new Bundle();
			args.putInt(ARG_SECTION_NUMBER, sectionNumber);
			fragment.setArguments(args);
			return fragment;
		}
	
		public PlaceholderFragment() 
		{
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 	
		{
			View rootView = inflater.inflate(R.layout.fragment_main, container,false);
	        return rootView;
		}
		
		@Override
		public void onAttach(Activity activity) 
		{
			super.onAttach(activity);
			((Main_Activity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
			
		}
	}
	
	/* Clear HN*/
	public void clear_HN_EditText_onClick (View onCreateView){
		System.out.println("Clear HN EditText Button");
		
	}
	
	/* Click : Check HN Button */
	public void check_HN_button_onClick (View onCreateView){
		System.out.println("Check HN Button Click Respond");
			    
		final String NAMESPACE = "http://tempuri.org/";
		final String URL = "http://10.6.21.70:8080/ekardexwservice1.asmx";
		final String SOAP_ACTION_GetHN = "http://tempuri.org/patient_GetByHN";
		final String METHOD_NAME_GetHN = "patient_GetByHN";
		
		// Section call web service (SOAP)
		final AlertDialog.Builder ad = new AlertDialog.Builder(this);
				
		final EditText cHN_id = (EditText)findViewById(R.id.HN_editText);
				
		// new thread for calling web services
		Thread HN_id_webservice = new Thread() {
			public void run(){
				SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_GetHN);
						 
				// use for add Property to HN_profile
				request.addProperty("HN", cHN_id.getText().toString());
				System.out.println("HN ID: " + cHN_id.getText().toString());
						
				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
						
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);
				envelope.bodyOut = request;
				System.out.println("Setting Complete");
				
				try{
					HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
					androidHttpTransport.call(SOAP_ACTION_GetHN, envelope);
					System.out.println("Send HN to server");
					SoapObject resultSOAP = (SoapObject)envelope.getResponse();
					System.out.println("Receive data already");
							
					if(resultSOAP != null){
						SoapObject result = (SoapObject)envelope.bodyIn;
						final String txtResult = result.toString();
						final String txtHN = result.getProperty(0).toString();
						System.out.println(envelope.bodyIn.toString());	
						
						CHN_Profile.HN = result.getProperty(5).toString();
						CHN_Profile.PatientFName = result.getProperty(6).toString();
						CHN_Profile.PatientLName = result.getProperty(7).toString();
						CHN_Profile.PatientGender = result.getProperty(9).toString();
						CHN_Profile.BedNoCurrent = result.getProperty(14).toString();
						
						System.out.println(CHN_Profile.HN);
						System.out.println(CHN_Profile.PatientFName);
						System.out.println(CHN_Profile.PatientLName);
						System.out.println(CHN_Profile.BedNoCurrent);
						System.out.println(CHN_Profile.PatientGender);
										
						get_HN = true;
						
					}else{
						// runOnUiThread for showing message on UI for No Respond form web service
						get_HN = false;
						runOnUiThread(new Runnable(){
							public void run(){
								ad.setTitle("Message Response");
								ad.setMessage("No Response");
								ad.setPositiveButton("OK", null);
								ad.show();
							}
						});
					}
				}
				catch (IOException e) {
					e.printStackTrace();
				}catch (XmlPullParserException e){
					e.printStackTrace();
				}
				catch (Exception e) {
			        e.printStackTrace();
			        
			        // runOnUiThread for showing message on UI
					runOnUiThread(new Runnable(){
						public void run(){
							ad.setTitle("Message Response");
							ad.setMessage("ERROR");
							ad.setPositiveButton("OK", null);
							ad.show();
						}
					});
			    }	
			}		
		};
		HN_id_webservice.start();
		new Handler().postDelayed(new Runnable(){
			public void run(){
				/* get HN's Profile succeed and go to check HN's Profile*/
				if (get_HN == true){
					
					/* Change to activity profile page */
					HN_Profile HN_Profile_Fragment = new HN_Profile();
					
					FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
			        fragmentTransaction.replace(android.R.id.content, HN_Profile_Fragment,"newFragment");
			        fragmentTransaction.addToBackStack("newFragment");
			        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			        fragmentTransaction.commit();
				}
			}
		},2000);
	}
	
	/* Click Administration Button */
	public void administration_button_onClick(View onCreateView){
		System.out.println("administration_button");
		
		Configuration config = getResources().getConfiguration();
		FragmentManager fragmentManager = getFragmentManager();
	    final android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
		
		
		final String NAMESPACE = "http://www.w3schools.com/webservices/";
		final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
		final String SOAP_ACTION = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
		final String METHOD_NAME = "CelsiusToFahrenheit";
		
		// Section call web service (SOAP)
		final AlertDialog.Builder ad = new AlertDialog.Builder(this);
				
		final EditText cHN_id = (EditText)findViewById(R.id.HN_editText);
		
		get_HN = false;
				
		// new thread for calling web services
		Thread HN_id_webservice = new Thread() {
			public void run(){
				SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
						 
				// use for add Property to HN_profile
				request.addProperty("Celsius", cHN_id.getText().toString());
				System.out.println("HN ID: " + cHN_id.getText().toString());
						
				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
						
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);
				envelope.bodyOut = request;
				System.out.println("Setting Complete");
				
				try{
					HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
					androidHttpTransport.call(SOAP_ACTION, envelope);
					System.out.println("Send HN to server");
					SoapPrimitive resultSOAP = (SoapPrimitive)envelope.getResponse();
					System.out.println("Receive data already");
							
					if(resultSOAP != null){
						get_HN = true;
						SoapObject result = (SoapObject)envelope.bodyIn;
						final String txtResult = result.toString();
						System.out.println(envelope.bodyIn.toString());					
					}else{
						// runOnUiThread for showing message on UI for No Respond form web service
						runOnUiThread(new Runnable(){
							public void run(){
								ad.setTitle("Message Response");
								ad.setMessage("No Response");
								ad.setPositiveButton("OK", null);
								ad.show();
							}
						});
					}
				}
				catch (IOException e) {
					e.printStackTrace();
				}catch (XmlPullParserException e){
					e.printStackTrace();
				}
				catch (Exception e) {
			        e.printStackTrace();
			        
			        // runOnUiThread for showing message on UI
					runOnUiThread(new Runnable(){
						public void run(){
							ad.setTitle("Message Response");
							ad.setMessage("ERROR");
							ad.setPositiveButton("OK", null);
							ad.show();
						}
					});
			    }	
			}		
		};
		HN_id_webservice.start();
		new Handler().postDelayed(new Runnable(){
			public void run(){
				/* get HN's Profile succeed and go to check HN's Profile*/
				if (get_HN == true){
					/* change to another Fragment */
					HN_Profile HN_Profile_Fragment = new HN_Profile();
					
					FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
			        fragmentTransaction.replace(android.R.id.content, HN_Profile_Fragment,"newFragment");
			        fragmentTransaction.addToBackStack("newFragment");
			        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			        fragmentTransaction.commit();
				}
			}
		},2000);
		
	}
}